package com.efounder.chat.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.adapter.MobileShareFirstAdapter;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.ShareBean;
import com.efounder.chat.service.SystemInfoService;
import com.efounder.chat.struct.StructFactory;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.utils.ResStringUtil;

import java.util.ArrayList;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_PASSWORD;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

/**
 * 选择好友群聊的baseactiviry（好友名片，群名片）
 *
 * @author yqs
 * 2018/10/15
 */

public abstract class SelectBaseActivity extends BaseActivity {

    private static final int SELECT_FRIEND = 88;
    private static final int SELECT_GROUP = 90;
    private MobileShareFirstAdapter mAdapter;
    private List<ShareBean> dataList;
    private List<ShareBean> topList;
    private TextView tvTitle;
    private TextView tvCancel;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wechatview_activity_select_base);
        initView();
        checkIsLogin();
    }

    private void initView() {
        //标题
        tvTitle = (TextView) this.findViewById(R.id.tv_title);
        tvCancel = (TextView) findViewById(R.id.tv_save);
        tvCancel.setVisibility(View.VISIBLE);
        tvCancel.setText(R.string.common_text_cancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        recyclerView = (RecyclerView) findViewById(R.id.recycleview);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    public void setBaseTitle(String text) {
        tvTitle.setText(text);
    }

    private void checkIsLogin() {
        String chatUserID = EnvironmentVariable.getProperty(CHAT_USER_ID);
        String chatPassword = EnvironmentVariable.getProperty(CHAT_PASSWORD);
        if (null == chatUserID || "".equals(chatUserID)
                || null == chatPassword || "".equals(chatPassword)) {
            //用户没有登陆 跳转登录界面
            new AlertDialog.Builder(this).setTitle(R.string.common_text_hint)
                    .setMessage(ResStringUtil.getString(R.string.chat_not_login_after_share))
                    .setCancelable(false)
                    .setPositiveButton(R.string.chat_go_login, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent();
                            try {
                                intent.setClass(SelectBaseActivity.this, Class.forName("com.efounder.activity.Login_withTitle"));
                                startActivity(intent);
                                finish();
                            } catch (ClassNotFoundException e) {
                                e.printStackTrace();
                            }
                        }
                    })
                    .setNeutralButton(R.string.common_text_back, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .show();
            return;
        } else {
            initShowListData();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    protected void initShowListData() {
        dataList = new ArrayList<>();
        topList = new ArrayList<>();
        ShareBean bean1 = new ShareBean.Builder().name(ResStringUtil.getString(R.string.chat_choose_friend)).type(ShareBean.SHARE_TYPE_SELECT_FRIEND).build();
        ShareBean bean2 = new ShareBean.Builder().name(ResStringUtil.getString(R.string.chat_choose) + getString(R.string.chat_room_name))
                .type(ShareBean.SHARE_TYPE_SELECT_GROUP).build();

        ShareBean bean4 = new ShareBean.Builder().name(ResStringUtil.getString(R.string.chat_lately)).type(ShareBean.SHARE_TYPE_RECENT).build();
        topList.add(bean1);
        topList.add(bean2);
        topList.add(bean4);
        dataList.addAll(topList);

        List<ChatListItem> lists = SystemInfoService.CHATITEMLIST;
        if (lists != null) {
            for (int i = 0; i < lists.size(); i++) {
                ChatListItem item = lists.get(i);
                if (item.getChatType() == StructFactory.TO_USER_TYPE_PERSONAL) {
                    if (item.getUser() != null && item.getUser().getType() == 1) {
                        if (!showPublicNumberUser()) {
                            continue;
                        }
                    }
                }
                ShareBean bean = new ShareBean.Builder().type(ShareBean.SHARE_TYPE_CHAT).name(item.getName())
                        .chatId(item.getUserId()).chatType(item.getChatType()).icon(item.getAvatar()).build();
                dataList.add(bean);
            }
        }

        mAdapter = new MobileShareFirstAdapter(this, dataList);
        recyclerView.setAdapter(mAdapter);
        mAdapter.setOnitemClickListener(new MobileShareFirstAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int posotion, ShareBean shareBean) {
                clickItem(posotion, shareBean);
            }
        });
    }

    //点击事件
    protected void clickItem(int position, ShareBean shareBean) {
        if (shareBean.getType().equals(ShareBean.SHARE_TYPE_SELECT_FRIEND)) {
            Intent intent = new Intent(this, SelectFriendActivity.class);
            intent.putExtra("isSingleMode", true);
            startActivityForResult(intent, SELECT_FRIEND);
        } else if (shareBean.getType().equals(ShareBean.SHARE_TYPE_SELECT_GROUP)) {
            Intent intent = new Intent(this, SelectGroupActivity.class);
            startActivityForResult(intent, SELECT_GROUP);
        } else if (shareBean.getType().equals(ShareBean.SHARE_TYPE_CHAT)) {
            //  sendMessage(shareBean.getChatId(), shareBean.getChatType());
            completeSelected(shareBean);

        }
    }

    /**
     * 重写选择完成的方法
     *
     * @param shareBean
     */
    public abstract void completeSelected(ShareBean shareBean);

    /**
     * 重写是否需要显示最近聊天中的应用号
     */
    public abstract boolean showPublicNumberUser();


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && (requestCode == SELECT_GROUP || requestCode == SELECT_FRIEND)) {
            if (data != null && data.hasExtra("userId")) {
                //选择好友
                ShareBean shareBean = new ShareBean.Builder()
                        .name(data.getStringExtra("nickName"))
                        .type(ShareBean.SHARE_TYPE_CHAT)
                        .chatId(data.getIntExtra("userId", 0))
                        .chatType(StructFactory.TO_USER_TYPE_PERSONAL)
                        .build();
                completeSelected(shareBean);
            } else {
                //选择群组
                if (data != null && data.hasExtra("groupId")) {
                    ShareBean shareBean = new ShareBean.Builder()
                            .name(data.getStringExtra("groupName"))
                            .type(ShareBean.SHARE_TYPE_CHAT)
                            .chatId(data.getIntExtra("groupId", 0))
                            .chatType(StructFactory.TO_USER_TYPE_GROUP)
                            .build();
                    completeSelected(shareBean);
                }
            }
        }
    }
}
